package com.example.dell.jakatra.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;

/**
 * Created by liangjianwei on 2017/12/28.
 */

public class GoogleLoginManager {
    private static GoogleLoginManager mGoogleLoginManager;

    public static GoogleLoginManager getInstance() {
        if (mGoogleLoginManager == null) {
            synchronized (GoogleLoginManager.class) {
                if (mGoogleLoginManager == null) {
                    mGoogleLoginManager = new GoogleLoginManager();
                }
            }
        }
        return mGoogleLoginManager;
    }


    public void login(AppCompatActivity appCompatActivity) {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        appCompatActivity.startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    private GoogleApiClient mGoogleApiClient;

    public void initLogin(AppCompatActivity appCompatActivity) {
        GoogleSignInOptions gso = new GoogleSignInOptions
                .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestId()
                .build();

        mGoogleApiClient = new GoogleApiClient
                .Builder(appCompatActivity)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        Log.i("robin", "onConnected:");
                    }

                    @Override
                    public void onConnectionSuspended(int i) {
                        Log.i("robin", "onConnectionSuspended:");
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        Log.i("robin", "onConnectionFailed:");
                    }
                })
                .enableAutoManage(appCompatActivity, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        Log.i("robin", "onConnectionFailed:");
                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
        mGoogleApiClient.connect();

    }

    public static int RC_SIGN_IN = 10001;
}
